<?php

namespace addons\shopro\controller\store;

use addons\shopro\exception\Exception;
use addons\shopro\model\OrderAftersaleLog;
use addons\shopro\model\Store as ModelStore;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;
use think\Db;

class Store extends Base
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];


    public function index()
    {
        $params = $this->request->get();
        $store = ModelStore::info();
        if (!$store) {
            $this->error('商家不存在');
        }

        //王猛 2022-2-8 14:52:37
        if ($this->request->isGet()) {
            $money_all = db('shopro_user_wallet_log')
                ->alias('a')
                ->join('shopro_order_item b','a.item_id=b.id')
                ->where(['a.store_id'=>$store['id'],'a.user_id'=>$this->auth->id,'a.wm_types'=>'sj','a.type'=>'xt','a.wallet_type'=>'money'])
                ->field('a.id as id,b.activity_type,b.goods_title,b.goods_num,b.goods_sku_text,b.goods_image,b.goods_price,a.wallet,a.ext,a.memo,a.createtime,b.createtime as orderCreatetime,b.money_pt,b.money_pt3,b.money_pt2,b.money_pt1,b.money_sys,b.money_sj,b.domoneytime,b.bind_domoneytime,b.pt_domoneytime')
                ->sum('wallet');
            $res = [
                'money_all'=>$money_all??0.00
            ];
        }

        $store = array_merge($store,$res);
        $store['banner_images_arr'] = explode(',', $store['banner_images']);
        $store['logo_images_arr'] = explode(',', $store['logo_images']);

        $this->success('获取成功', $store);
    }
    public function aftersale(){

        $params = $this->request->get();
        $order_info = Db::name('shopro_order')->where('id',$params['orderid'])->find();
        $order_item_info = Db::name('shopro_order_item')->where('order_id',$order_info['id'])->find();
        $store_info = Db::name('shopro_user_store')->where('store_id',$order_item_info['good_shopro_store_id'])->find();
        $aftersale_info = Db::name('shopro_order_aftersale')->where('order_id',$params['orderid'])->find();

        if ($params['type']=='1'){

            if ($store_info['user_id'] != (int)$this->auth->id){
                $this->error('权限不足');
            }
            $refund_money = bcmul($aftersale_info['goods_price'], $aftersale_info['goods_num'],2);

            if ($refund_money < 0) {
                $this->error('退款金额不能小于 0');
            }

            $aftersale = \app\admin\model\shopro\order\Aftersale::withTrashed()->canOper()->where('id', $aftersale_info['id'])->find();

            if (!$aftersale) {
                $this->error('售后单不存在或不可退款');
            }

            $order = \app\admin\model\shopro\order\Order::withTrashed()->with('item')->where('id', $aftersale->order_id)->find();

            if (!$order) {
                $this->error('订单不存在');
            }

            $items = $order->item;
            $items = array_column($items, null, 'id');

            // 当前订单已退款总金额
            $refunded_money = array_sum(array_column($items, 'refund_fee'));
            // 剩余可退款金额
            $refund_surplus_money = $order->pay_fee - $refunded_money;
            // 如果退款金额大于订单支付总金额
            if ($refund_money > $refund_surplus_money) {
                $this->error('退款总金额不能大于实际支付金额');
            }

            $orderItem = $items[$aftersale['order_item_id']];

            if (!$orderItem || in_array($orderItem['refund_status'], [
                    \app\admin\model\shopro\order\OrderItem::REFUND_STATUS_OK,
                    \app\admin\model\shopro\order\OrderItem::REFUND_STATUS_FINISH,
                ])) {
                $this->error('订单商品已退款，不能重复退款');
            }

            Db::transaction(function () use ($aftersale, $order, $orderItem, $refund_money, $refund_surplus_money) {
                $data = ['aftersale' => $aftersale, 'order' => $order, 'item' => $orderItem];
                \think\Hook::listen('aftersale_finish_before', $data);

                $aftersale->aftersale_status = \app\admin\model\shopro\order\Aftersale::AFTERSALE_STATUS_OK;    // 售后同意
                $aftersale->refund_status = \app\admin\model\shopro\order\Aftersale::REFUND_STATUS_FINISH;    // 售后同意退款
                $aftersale->refund_fee = $refund_money;     // 退款金额
                $aftersale->save();

                // 增加售后单变动记录
                OrderAftersaleLog::operAdd($order, $aftersale, $this->auth->getUserInfo(), 'admin', [
                    'reason' => '卖家同意退款',
                    'content' => '售后订单已退款',
                    'images' => []
                ]);

                $orderItem->aftersale_status = OrderItem::AFTERSALE_STATUS_OK;
                $orderItem->save();
                \addons\shopro\model\OrderAction::operAdd($order, $orderItem, $this->auth->getUserInfo(), 'admin', '商家同意售后退款');

                // 退款
                \app\admin\model\shopro\order\Order::startRefund($order, $orderItem, $refund_money, $this->auth->getUserInfo(), '商家同意售后退款');

                $data = ['aftersale' => $aftersale, 'order' => $order, 'item' => $orderItem];
                \think\Hook::listen('aftersale_finish_after', $data);
            });

            //开始-2022-2-10 Ripple 推送消息
            if ($order->platform_source == '2' || $order->platform_source == '3'){//抖音订单 或 快手订单
                $user_mobile = Db::name('user')->where(['id'=>$order->user_id])->value('mobile');
                if (empty($user_mobile)){
                    $msg_data = [
                        'goods_name' => $orderItem->goods_title,
                        'money' => $refund_money,
                        'time'=>'3'
                    ];
                    douyin_sms_refund($user_mobile,$msg_data);
                }
            }else{//微信订单

            }
            //结束-2022-2-10 Ripple 推送消息

            $this->success('操作成功');
        }
        if ($params['type']=='2'){
            $refuse_msg = '卖家拒绝了申请';


            $aftersale = \app\admin\model\shopro\order\Aftersale::withTrashed()->canOper()->where('id', $aftersale_info['id'])->find();

            if (!$aftersale) {
                $this->error('售后单不存在或不可拒绝');
            }

            $order = \app\admin\model\shopro\order\Order::withTrashed()->with('item')->where('id', $aftersale->order_id)->find();
            $orderItem = OrderItem::where('id', $aftersale->order_item_id)->find();
            if (!$order || !$orderItem) {
                $this->error('订单或订单商品不存在');
            }

            Db::transaction(function () use ($aftersale, $order, $orderItem, $refuse_msg) {
                // 售后单拒绝前
                $data = ['aftersale' => $aftersale, 'order' => $order, 'item' => $orderItem];
                \think\Hook::listen('aftersale_refuse_before', $data);

                $aftersale->aftersale_status = \app\admin\model\shopro\order\Aftersale::AFTERSALE_STATUS_REFUSE;    // 售后拒绝
                $aftersale->save();
                // 增加售后单变动记录
                OrderAftersaleLog::operAdd($order, $aftersale, $this->auth->getUserInfo(), 'admin', [
                    'reason' => '卖家拒绝售后',
                    'content' => $refuse_msg,
                    'images' => []
                ]);

                $orderItem->aftersale_status = OrderItem::AFTERSALE_STATUS_REFUSE;    // 拒绝售后
                $orderItem->save();

                \addons\shopro\model\OrderAction::operAdd($order, $orderItem, $this->auth->getUserInfo(), 'admin', '管理员拒绝订单售后：' . $refuse_msg);

                // 售后单拒绝后
                $data = ['aftersale' => $aftersale, 'order' => $order, 'item' => $orderItem];
                \think\Hook::listen('aftersale_refuse_after', $data);
            });

            $this->success('操作成功');
        }




    }
    
}
